package com.ruoyi.crm.freemaker.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.crm.sale.domain.CrmBusinessProduct;
import com.ruoyi.crm.sale.domain.CrmContract;
import com.ruoyi.crm.sale.service.ICrmBusinessProductService;
import com.ruoyi.crm.sale.service.ICrmContractService;
import com.ruoyi.crm.utils.MoneyUtil;

/**
 * 合同下载 Controller
 * 
 * @author ruoyi
 * @date 2021-09-06
 */
@Controller
@RequestMapping("/templates")
public class ContractDownloadController extends BaseController {
	
	@Autowired
	private ICrmContractService crmContractService;
	
	@Autowired
    private ICrmBusinessProductService crmBusinessProductService;
	
	
	private static final Logger log = LoggerFactory.getLogger(ContractDownloadController.class);

	
	/**
	 * 模板下载预览
	 */
	@PostMapping("/templatePreview")
	public String templatePreview(@RequestBody String templateName, Model model) {
		templateName = templateName.substring(0, templateName.lastIndexOf(".ftl"));
		
		CrmContract crmContract = new CrmContract();
		model.addAttribute("contract", crmContract);
		
		return templateName;
	}

	
	/**
	 * 套模板下载合同
	 */
	@PostMapping("/downloadContract")
	public String downloadContract(@RequestBody Map<String, Object> paramsMap, Model model) {
		long id = Long.valueOf(paramsMap.get("id").toString());
		String templatePath = paramsMap.get("template").toString();
		templatePath = templatePath.substring(0, templatePath.lastIndexOf(".ftl"));
		
		CrmContract crmContract = crmContractService.selectCrmContractById(id);
		crmContract.setMoneydx(MoneyUtil.toChinese(crmContract.getMoney().toString()));
		
		CrmBusinessProduct busPro = new CrmBusinessProduct();
		busPro.setBusinessId(id);
		busPro.setType((long)2);
		
		crmContract.setProductList(crmBusinessProductService.selectCrmBusinessProductList(busPro));
		
		model.addAttribute("contract", crmContract);
		
		return templatePath;
	}
	
	/**
	 * 查询所有合同模板
	 */
	@GetMapping("/contractList")
	@ResponseBody
	public List<Map<String, Object>> listConTemplates() {
		
		String path = RuoYiConfig.getProTemplateFile();
		File templatesPath = new File(path);
		
		if(!templatesPath.exists()) {
			templatesPath.mkdirs();
		}
		
		File[] templates = templatesPath.listFiles();
		
		List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
		Map<String, Object> temMap = null;
		for(File template : templates) {
			if(template.isFile()) {
				temMap = new HashMap<String, Object>();
				temMap.put("templateName", template.getName());
				listMap.add(temMap);
			}
		}
		return listMap;
	}
	
	/**
	 * 修改模板初始化
	 * @throws FileNotFoundException 
	 */
	@PostMapping("/editTemplateInit")
	@ResponseBody
	public Map<String, Object> editTemplateInit(@RequestBody String templateName){
		
		String path = RuoYiConfig.getProTemplateFile() + "/" + templateName;
		
		File template = new File(path);
		
		Map<String, Object> temMap = new HashMap<String, Object>();
		temMap.put("templateName", templateName);
		
		StringBuilder tempStr = new StringBuilder();
		BufferedReader reader = null;
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(new FileInputStream(template), "UTF-8");
			reader = new BufferedReader(isr);
			
			String lineStr;
			while((lineStr = reader.readLine()) != null) {
				lineStr+='\n';
				tempStr.append(lineStr);
			}
			temMap.put("content", tempStr);
			
		} catch (Exception e) {
			log.error("读取模板文件报错", e);
			e.printStackTrace();
		} finally {
			try {
				if(null != reader) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		
		return temMap;
	}
	
	/**
	 * 修改模板
	 * @throws FileNotFoundException 
	 */
	@PostMapping("/editTemplate")
	@ResponseBody
	public Map<String, Object> editTemplate(@RequestBody Map<String, Object> templateMap){
		
		Map<String, Object> result = new HashMap<String, Object>();
		
		String templateName = templateMap.get("templateName").toString();
		
		String path = RuoYiConfig.getProTemplateFile() + "/" + templateName;
		
		Writer temFile = null;
		try {
			temFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
			temFile.write(templateMap.get("content").toString());
			temFile.flush();
			result.put("result", true);
		} catch (IOException e) {
			log.error("写入模板文件报错", e);
			result.put("result", false);
			e.printStackTrace();
		} finally {
			try {
				if(null != temFile) {
					temFile.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		
		return result;
	}
	
	/**
	 * 删除模板
	 * @throws FileNotFoundException 
	 */
	@PostMapping("/deleteTemplate")
	@ResponseBody
	public Map<String, Object> deleteTemplate(@RequestBody String[] templateNames){
		Map<String, Object> result = new HashMap<String, Object>();
		
		for(String temPath : templateNames) {
			String path = RuoYiConfig.getProTemplateFile() + "/" +  temPath;
			
			File template = new File(path);
			
			if(template.exists()) {
				template.delete();
			}
			
			result.put("result", true);
		}
		
		return result;
	}
}
